package com.ejlchina.tool.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.doAfterTextChanged
import androidx.recyclerview.widget.GridLayoutManager
import com.adolf.androiddemo.databinding.FragmentDoorControlBinding
import com.huyuhui.fastble.data.BleDevice
import com.ejlchina.tool.adapter.DeviceAdapterRadio
import com.ejlchina.tool.base.BaseBindingFragment2
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.bean.DoorControlBean
import com.ejlchina.tool.singleton.GlobalConnectObject
import com.ejlchina.tool.util.COMMAND_DOOR_CONTROL_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_DOOR_CONTROL_GET_UPWARD
import com.ejlchina.tool.util.COMMAND_DOOR_CONTROL_SET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_DOOR_CONTROL_SET_UPWARD
import com.ejlchina.tool.util.bytearray.intTo32HexStringLE
import com.ejlchina.tool.util.bytearray.intToByteHexString
import com.ejlchina.tool.util.bytearray.readInt32LE
import com.ejlchina.tool.util.getBitValueFrom8Bits
import com.ejlchina.tool.util.setBitValue
import com.ejlchina.tool.view.GridItemDecoration

class DoorControlFragment: BaseBindingFragment2<FragmentDoorControlBinding>() {
    
    private val doorControlBean = DoorControlBean()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
        initData()
    }

    private fun initViews(){
        setHeadTitle("门机控制")
        setRightIconVisibility(View.GONE)
        initListeners()
    }

    private fun initListeners(){
        binding.msButtonOpen.setOnCheckedChangeListener { _, isChecked ->
            doorControlBean.buttonOpenDoor = isChecked
            binding.layoutAuthTime.visibility = if (isChecked) View.GONE else View.GONE //授权时间隐藏掉
        }
        binding.msBodyOpen.setOnCheckedChangeListener { _, isChecked ->
            doorControlBean.bodyOpenDoor = isChecked
        }
        binding.msAntiPinch.setOnCheckedChangeListener { _, isChecked ->
            doorControlBean.bodyAntiPinch = isChecked
        }

        binding.btnConfirm.setOnClickListener {
            setDoorControlData(deviceAdapter.getSelectDevice())
        }
        binding.etAuthorizeTime.doAfterTextChanged { editable ->
            editable?.let {
                val text = it.toString()
                if (text.isNotEmpty()){
                    doorControlBean.authorizationTime = text.toInt()
                }
            }

        }
    }

    private fun initData(){
        initDevices()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initDevices(){
        deviceAdapter = DeviceAdapterRadio(GlobalConnectObject.getCurrentConnectDeviceList()){
            getDoorControlData(it)
        }
        binding.rvDevices.apply {
            adapter = deviceAdapter
            layoutManager = GridLayoutManager(requireContext(), 3)
            if (itemDecorationCount == 0) {
                addItemDecoration(GridItemDecoration(3, 11, 11))
            }
        }
    }

    override fun whenReceiveCommand(bleDevice: BleDeviceBean,command: String, dataByteArray: ByteArray) {
        super.whenReceiveCommand(bleDevice,command, dataByteArray)
        when(command){
            COMMAND_DOOR_CONTROL_GET_UPWARD -> {
                setDoorControlData(dataByteArray)
                setUIData()
            }
            COMMAND_DOOR_CONTROL_SET_UPWARD -> {
                setResultToast(dataByteArray[dataByteArray.size - 1].toInt())
            }
        }
        dismissLoading()
    }


    private fun setDoorControlData(byteArray: ByteArray){
        val doorByte = byteArray[0]
        doorControlBean.buttonOpenDoor = getBitValueFrom8Bits(doorByte,0) == 1
        doorControlBean.bodyOpenDoor = getBitValueFrom8Bits(doorByte,1) == 1
        doorControlBean.bodyAntiPinch = getBitValueFrom8Bits(doorByte,2) == 1
        doorControlBean.authorizationTime = byteArray.readInt32LE(1) / 1000
    }

    private fun setUIData(){
        binding.msButtonOpen.isChecked = doorControlBean.buttonOpenDoor
        binding.msBodyOpen.isChecked = doorControlBean.bodyOpenDoor
        binding.msAntiPinch.isChecked = doorControlBean.bodyAntiPinch
        binding.layoutAuthTime.visibility = if (binding.msButtonOpen.isChecked) View.GONE else View.GONE
        binding.etAuthorizeTime.setText(doorControlBean.authorizationTime.toString())
    }

    private fun getDoorControlData(bleDevice: BleDeviceBean){
        showLoading()
        getCommandData(bleDevice,COMMAND_DOOR_CONTROL_GET_DOWNWARD)
    }

    private fun setDoorControlData(bleDevice: BleDeviceBean){
        showLoading()
        setCommandData(bleDevice,COMMAND_DOOR_CONTROL_SET_DOWNWARD,getResultData())
    }

    private fun getResultData(): String{
        var doorControlValue = 0
        if (doorControlBean.buttonOpenDoor){
            doorControlValue = setBitValue(doorControlValue,0)
        }
        if (doorControlBean.bodyOpenDoor){
            doorControlValue = setBitValue(doorControlValue,1)
        }
        if (doorControlBean.bodyAntiPinch){
            doorControlValue = setBitValue(doorControlValue,2)
        }
        return intToByteHexString(doorControlValue) + intTo32HexStringLE(doorControlBean.authorizationTime * 1000)
    }
    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup): FragmentDoorControlBinding {
        return FragmentDoorControlBinding.inflate(inflater,container,true)
    }
}